<template>
  <base-modal :show.sync="batchUpdateCustomerDialog" :width="width" class="biz-batch-update-dialog" @closed="closeModal">
    <div slot="title">
      <el-popover placement="bottom-start" popper-class="batch-update-customer-modal-header" trigger="hover">
        <h3 class="customized-batch-update-customer-modal-header" slot="reference">{{title ? title : $t('component.bizBatchUpdate.title')}}<i class="iconfont icon-help"></i></h3>

        <div class="tips">
          <p>{{$t('component.bizBatchUpdate.tips[0]')}}</p>
          <p>{{$t('component.bizBatchUpdate.tips[1]')}}</p>
          <p>{{$t('component.bizBatchUpdate.tips[2]')}}</p>
        </div>
      </el-popover>
    </div>
    <div class="main-content">
      <p>
        <template v-if="hasSelectedData || isPostBatch">
          <strong v-html="tip" class="info-item"></strong>
          <a href="javascript:;" @click="downloadData">{{$t('common.base.download')}}</a>
          <strong class="info-item" v-if="!hasSelectedData">{{$t('component.bizBatchUpdate.mainContent.emptyTemp')}}</strong>
        </template>
        <template v-else>
          <strong class="info-item">{{$t('component.bizBatchUpdate.mainContent.step1[0]')}}</strong>
          <a href="javascript:;" @click="downloadBlank">{{$t('common.base.download')}}</a>
          <strong class="info-item">{{$t('component.bizBatchUpdate.mainContent.emptyTemp')}}</strong>
        </template>
      </p>
      
      <p>{{$t('component.bizBatchUpdate.mainContent.step2')}}</p>

      <div class="base-import-file">
        <p>{{fileName}}</p>
        <el-button type="primary" @click="choose" :disabled="pending">{{$t('component.bizBatchUpdate.mainContent.choiceFile')}}</el-button>
        <input type="file" ref="file" @change="change"
               accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
      </div>
      <ul class="error-message" v-if="errors.length">
        <li>{{$t('common.base.importFail')}}！</li>
        <li v-for="(item, index) in errors" :key="index">{{item}}</li>
      </ul>
    </div>
    <div slot="footer" class="import-footer">
      <el-button class="btn btn-text" @click="batchUpdateCustomerDialog = false">{{$t('common.base.close')}}</el-button>
      <el-button type="primary" :disabled="pending" @click="upload" :loading="pending">{{pending ? $t('common.base.importing') : $t('common.base.import')}}</el-button>
    </div>
    <div ref="bridge" style="display: none;"></div>
  </base-modal>
</template>

<script>
import i18n from '@src/locales';
import Uploader from '@src/util/uploader';
import Platform from '@src/platform';
import { formatDate } from 'pub-bbx-utils';
import { safeNewDate } from '@src/util/time';
import { exportAlert } from '@src/util/alert';

export default {
  name: 'biz-batch-update',
  data() {
    return {
      fileName: '',
      pending: false,
      file: null,
      errors: [],
      batchUpdateCustomerDialog: false,
    }
  },
  props: {
    width: {
      type: String,
      default: '600px'
    },
    selectedIds: {
      type: Array,
      default: () => ([]),
    },
    totalItems: {
      type: Number,
      default: 0,
    },
    action: {
      type: String,
      default: '',
    },
    buildDownloadParams: {
      type: Function,
      default: () => {
        return function () {}
      },
    },
    /** 下载批量更新模板url */
    batchUpdateTemplate: {
      type: String,
      default: '',
    },
    /** 批量更新参数 */
    uploadParamObject: {
      type: Object,
      default:  () => ({}),
    },
    /** 是否需要post请求 */
    isPostBatch: {
      type:Boolean,
      default: false
    },
    title: {
      type: String,
      default: '',
    },
    moduleTitle: {
      type: String,
      default: '',
    },
  },
  computed: {
    exportType() {
      if (this.selectedIds.length) {
        return 'exportSelect';
      }
      return 'exportAll';
    },
    selectedCount() {
      if (this.selectedIds.length) {
        return this.selectedIds.length;
      }
      return this.totalItems;
    },
    tip() {
      if (this.selectedIds.length) {
        return i18n.t('component.bizBatchUpdate.mainContent.step1[1]', {length: this.selectedIds.length})
      }
      return i18n.t('component.bizBatchUpdate.mainContent.step1[0]');
    },
    hasSelectedData() {
      return this.selectedIds.length > 0;
    }

  },
  methods: {
    closeModal() {
      this.file = null;
      this.fileName = '';
      this.errors = [];
    },
    choose(){
      this.$refs.file.value = null;
      this.$refs.file.click();
    },
    openBatchUpdateCustomerDialog() {
      this.batchUpdateCustomerDialog = true;
    },
    downloadData() {
      // let params = {
      //   count: this.selectedCount,
      //   exportType: this.exportType,
      //   data: '',
      // };

      // if (this.exportType === 'exportSelect') {
      //   params.data = this.selectedIds.join(',');
      // } else {
      //   params.data = this.buildDownloadParams();
      // }
      // window.location.href = `/product/importCover/export?data=${encodeURI(JSON.stringify(params))}`;
      let params;
      let url;
      if (this.batchUpdateTemplate) {
        params = {
          idList: this.selectedIds,
          ...this.uploadParamObject
        };
        url = this.batchUpdateTemplate
      } else {
        params = this.selectedIds;
        url =  '/product/importCover/export';
      }

      let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
      let fileName = i18n.t('component.bizBatchUpdate.downloadData.filename', {
        neme: date,
        module: this.moduleTitle? this.moduleTitle : i18n.t('common.base.product')
      });

      this.$http.post(url, params, true, {responseType: 'blob'})
        .then(blob => {
          let link = document.createElement('a');
          let url = URL.createObjectURL(blob);
          link.download = fileName;
          link.href = url;
          this.$refs.bridge.appendChild(link);
          link.click();

          setTimeout(() => {
            URL.revokeObjectURL(url);
            this.$refs.bridge.removeChild(link);
          }, 150);
        })
        .catch(err => console.error(err));
    },
    downloadBlank() {
      window.location.href = '/product/importBlankCoverExport/exportNew';
    },
    async upload(){
      try {
        if(null == this.file || !(this.file instanceof File)) return Platform.alert(i18n.t('common.placeholder.selectImportFile'));

        if (!await this.$platform.confirm(i18n.t('common.base.tip.batchImportConfirm'))) return;

        this.pending = true;
        Uploader.upload(this.file, this.action, {
          validateStorage: false,
          ...this.uploadParamObject
        })
          .then(result => {
            
            if(!result.status){
              
              this.batchUpdateCustomerDialog = false;
              
              exportAlert(result.message)
              
            }else{
              Platform.alert(result.message);
              this.errors = result.data || [];
              // Platform.alert(`导入失败！\n${data.join('\n')}`);
            }
            
            this.pending = false;
            
          })
          .catch(err => {
            console.error(err)
          })
          .finally(() => {
            this.pending = false;
          })

      } catch (e) {
        console.error('upload catch e', e);
      }
    },
    change(event){
      const files = event.target.files;
      if (!files || !files.length) return;
      let file = files[0];

      this.errors = [];
      this.fileName = file.name;
      this.file = file
    },
  },
}
</script>

<style lang="scss">

  .customized-batch-update-customer-modal-header {
    display: inline-block;
    .iconfont {
      margin: 4px;
      position: relative;
      top: 1px;
    }
  }

  .batch-update-customer-modal-header {
    font-size: 12px;
    p {
      margin: 0;
      line-height: 20px;
    }
  }

  .biz-batch-update-dialog {
    .base-modal-header {
      justify-content: space-between;
    }
    .main-content {
      font-size: 12px;
      padding: 20px 20px 0 20px;

      .info-item {
        font-weight: normal;
        span {
          padding: 0 5px;
          color: blue;
        }
      }
    }

    .base-import-file{
      display: flex;
      flex-flow: row nowrap;
      margin-bottom: 15px;

      &:last-child{
        margin-bottom: 5px;
      }
      p {
        flex: 1;
        line-height: 24px;
        padding: 3px 6px;

        border: 1px solid #d5d5d5;
        background-color: #f0f0f0;
        border-right: none;
        margin: 0;
        border-radius: 2px 0 0 2px;
      }

      .el-button{
        border-radius: 0 2px 2px 0;
      }

      input[type='file']{
        display: none;
      }
    }

    .error-message {
      max-height: 100px;
      overflow-y: auto;
      padding: 0;
      li {
        list-style: none;
      }
    }

    .base-modal-footer {
      padding: 15px 20px;
      .import-footer {
        display: flex;
        justify-content: flex-end;

        button {
          min-width: 80px;
        }
      }

    }
  }

</style>
